package cn.yusei.teamTribe.service.relation;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.dao.relation.RelationDAO;
import cn.yusei.teamTribe.dao.relation.RelationRequestDAO;
import cn.yusei.teamTribe.dao.relation.po.RelationPO;
import cn.yusei.teamTribe.dao.relation.po.RelationRequestPO;
import cn.yusei.teamTribe.entity.Relation;

@Service
public class RelationService {

	@Autowired
	private RelationDAO relationDAO;
	@Autowired
	private RelationRequestDAO relationRequestDAO;
	
	/**
	 * 用户同意好友申请后将好友关系添加到数据库
	 * 
	 * @param relationRequestId  被同意的申请的 id
	 * @return
	 */
	public int add(int relationRequestId) {
		RelationRequestPO relationRequestPO = relationRequestDAO.selectById(relationRequestId);
		if(relationRequestPO == null)
			return ResponseCode.SERVER_ERROR;               //因为这个 add 方法由服务器调用，如果对应的 relaionRequest 不存在表示发生了异常
		RelationPO relationPO = new RelationPO();
		int minId = Math.min(relationRequestPO.getId1(), relationRequestPO.getId2());
		int maxId = Math.max(relationRequestPO.getId1(), relationRequestPO.getId2());
		relationPO.setId1(minId);
		relationPO.setId2(maxId);
		if(relationDAO.exists(relationPO) != null)           //这一对好友关系不应该已经存在了
			return ResponseCode.SERVER_ERROR;
		relationDAO.insert(relationPO);
		return ResponseCode.REQUEST_SUCCESSED;
	}

	public int delete(Relation friendRelation) {
		RelationPO relationPO = new RelationPO();
		relationPO.setId1(friendRelation.getId1());
		relationPO.setId2(friendRelation.getId2());
		if(relationDAO.exists(relationPO) == null)
			return ResponseCode.REQUEST_SUCCESSED;
		relationDAO.delete(relationPO);
		return ResponseCode.REQUEST_SUCCESSED;
	}

	/**
	 * 获取指定 id 用户的所有好友的 id
	 * 
	 * @param id
	 * @return
	 */
	public List<Integer> get(int id) {
		List<Integer> ids = new ArrayList<Integer>();
		RelationPO[] relationPOs = relationDAO.selectById(id);
		for(RelationPO relationPO : relationPOs)
		{
			if(relationPO.getId1() == id)
				ids.add(Integer.valueOf(relationPO.getId2()));
			else
				ids.add(Integer.valueOf(relationPO.getId1()));
		}
		return ids;
	}
	
	
	
}
